package com.example.grpcserver.service;

import com.example.grpc.proto.*;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@GrpcService
public class UserServiceImpl extends UserServiceGrpc.UserServiceImplBase {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    // 模拟数据库
    private final Map<Integer, UserResponse> userMap = new HashMap<>();
    private final AtomicInteger idGenerator = new AtomicInteger(1);

    public UserServiceImpl() {
        // 初始化一些测试数据
        createUser("张三", 25, "zhangsan@example.com");
        createUser("李四", 30, "lisi@example.com");
        createUser("王五", 35, "wangwu@example.com");
    }

    private UserResponse createUser(String name, int age, String email) {
        int id = idGenerator.getAndIncrement();
        UserResponse user = UserResponse.newBuilder()
                .setId(id)
                .setName(name)
                .setAge(age)
                .setEmail(email)
                .build();
        userMap.put(id, user);
        return user;
    }

    @Override
    public void getUser(UserRequest request, StreamObserver<UserResponse> responseObserver) {
        int userId = request.getId();
        logger.info("接收到获取用户请求，用户ID: {}", userId);
        
        UserResponse user = userMap.get(userId);
        if (user != null) {
            responseObserver.onNext(user);
            logger.info("返回用户信息: {}", user);
        } else {
            logger.warn("用户不存在，ID: {}", userId);
            responseObserver.onNext(UserResponse.newBuilder().build());
        }
        
        responseObserver.onCompleted();
    }

    public void createUser(CreateUserRequest request, StreamObserver<CreateUserResponse> responseObserver) {
        logger.info("接收到创建用户请求: {}", request);
        
        UserResponse user = createUser(request.getName(), request.getAge(), request.getEmail());
        CreateUserResponse response = CreateUserResponse.newBuilder()
                .setUser(user)
                .setSuccess(true)
                .setMessage("用户创建成功")
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
        
        logger.info("用户创建成功: {}", user);
    }

    public void listUsers(Empty request, StreamObserver<UserListResponse> responseObserver) {
        logger.info("接收到获取所有用户请求");
        
        List<UserResponse> users = new ArrayList<>(userMap.values());
        UserListResponse response = UserListResponse.newBuilder()
                .addAllUsers(users)
                .build();
        
        responseObserver.onNext(response);
        responseObserver.onCompleted();
        
        logger.info("返回用户列表，共 {} 个用户", users.size());
    }
}